﻿using JWT.Algorithms;
using JWT.Builder;
using Knowledge.EF.Back.Models;
using Knowledge.EF.Back.Models.DB;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Knowledge.EF.Back.Auth
{
    public class Author : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var B = filterContext.HttpContext.Request.Headers;
            if (B.ContainsKey("Authorization") && B["Authorization"].Count > 0)
            {
                var C = B["Authorization"][0];

                if (string.IsNullOrEmpty(C))
                {
                    filterContext.Result = new JsonResult(new BaseResult { Code = 201, Message = "Token空的" });
                }
                else
                {
                    var D = JWTDecode(C);
                    if (string.IsNullOrEmpty(D))
                    {
                        filterContext.Result = new JsonResult(new BaseResult { Code = 201, Message = "无效的Token" });
                    }
                }
            }
            else
            {
                filterContext.Result = new JsonResult(new BaseResult { Code = 201, Message = "未传递Token" });
            }
        }

        public string JWTDecode(string token)
        {

            try
            {
                var json = new JwtBuilder()
                .WithAlgorithm(new HMACSHA256Algorithm()) // 设置JWT算法
                .WithSecret(ConfigHelper.Configuration["secret"])//校验的秘钥
                .MustVerifySignature()//必须校验秘钥
                .Decode(token);//解析token
                //输出解析后的json
                Console.WriteLine($"方式二解析后的json为：[{json}]");
                return json;
            }
            catch (Exception ex)
            {
                Console.WriteLine("解析json时出现异常：" + ex.ToString());
                return "";

            }

        }
    }
}
